﻿/*
   　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class Basic_Boar_changeLog
    {
        public static BLL.Basic_Boar_changeLog category = new BLL.Basic_Boar_changeLog();
        public static Model.Basic_Boar_changeLog model = new Model.Basic_Boar_changeLog();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public Basic_Boar_changeLog()
        {
        }

        public Basic_Boar_changeLog(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {

           string type =PageValidate.InputText(request["type"], 50);
            model.remarks = type; 
            model.BoarId = PageValidate.InputText(request["bid"], 50);
            if (type == "In") {
             
                model.InTime = DateTime.Now;
                model.InDormId = PageValidate.InputText(request["DormId"], 50);
                model.InCorralId = PageValidate.InputText(request["CorralId"], 250);
                string sqlstr = "       SELECT * FROM dbo.Basic_boar WHERE dormId = '" + model.InDormId + "' AND corralId = '" + model.InCorralId + "'  ";
               DataSet ds= DBUtility.DbHelperSQL.Query(sqlstr);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    return XhdResult.Error(ds.Tables[0].Rows[0]["barcode"].ToString()+"已经占用此位置!").ToString();
                }
                else
                {
                    string sql = "UPDATE dbo.Basic_boar SET dormId='" + model.InDormId + "' ,corralId='" + model.InCorralId + "' WHERE id='" + model.BoarId + "'";
                    DBUtility.DbHelperSQL.ExecuteSql(sql);
                    model.id = Guid.NewGuid().ToString();
                    model.accpetPerson = emp_name;
                    category.Add(model);
                }
            }
            if (type == "Out") { 
                string sql = "UPDATE dbo.Basic_boar SET dormId='' ,corralId='' WHERE id='" + model.BoarId + "' ;";
                sql += " UPDATE dbo.Basic_Boar_changeLog SET OutTime=GETDATE(),OutDormId='" + emp_name+"' WHERE BoarId='" + model.BoarId + "' AND OutTime IS NULL ";
                DBUtility.DbHelperSQL.ExecuteSql(sql);
            }
            if (type == "Change") {
              string  Nobid =PageValidate.InputText(request["Nobid"], 50);
                if (Nobid == "Y")//直接入舍{}
                {
                    model.InTime = DateTime.Now;
                    model.InDormId = PageValidate.InputText(request["DormId"], 50);
                    model.InCorralId = PageValidate.InputText(request["CorralId"], 50);
                    string sql = "UPDATE dbo.Basic_boar SET dormId='" + model.InDormId + "' ,corralId='" + model.InCorralId + "' WHERE id='" + model.BoarId + "'";
                    DBUtility.DbHelperSQL.ExecuteSql(sql);
                    model.id = Guid.NewGuid().ToString();
                    model.accpetPerson = emp_name;
                    category.Add(model);
                }
                else if (Nobid == "N") { //调换

                    //   DataSet ds = category.GetList(" dormId='" + PageValidate.InputText(request["DormId"], 50) + "' and corralId='" + PageValidate.InputText(request["CorralId"], 50) + "'");
                    string DormId = PageValidate.InputText(request["DormId"], 50);
                    string CorralId = PageValidate.InputText(request["CorralId"], 50);
                    string bid = PageValidate.InputText(request["bid"], 50);
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine(" --先取出选择的舍/栏 的种禽  ");
                    sb.AppendLine(" DECLARE @Old_Id VARCHAR(50)  ");
                    sb.AppendLine(" SELECT @Old_Id=id FROM dbo.Basic_boar WHERE dormId='"+ DormId + "' AND corralId='"+ CorralId + "'  ");
                    sb.AppendLine("   ");
                    sb.AppendLine(" DECLARE @dormId VARCHAR(50)  ");
                    sb.AppendLine(" DECLARE @corralId	 VARCHAR(50)  ");
                    sb.AppendLine(" --再取出当前种禽的 舍/栏  ");
                    sb.AppendLine(" SELECT @dormId=dormId,@corralId=corralId FROM Basic_boar WHERE id='"+ bid + "'  ");
                    sb.AppendLine("   ");
                    sb.AppendLine(" IF @dormId='" + DormId + "' AND @corralId='" + CorralId + "'  ");
                    sb.AppendLine(" BEGIN  ");
                    sb.AppendLine(" RAISERROR('选择的舍/栏不能完全相同!',18,6)   ");
                    sb.AppendLine(" RETURN;  ");
                    sb.AppendLine(" END  "); 
                    sb.AppendLine(" --释放 需要的 舍/栏  把当前的舍/栏更新给需要的(调换)  ");
                    sb.AppendLine(" UPDATE Basic_boar SET dormId=@dormId,corralId=@corralId WHERE id=@Old_Id  ");
                    sb.AppendLine(" --出栏  ");
                    sb.AppendLine(" UPDATE Basic_Boar_changeLog SET	 OutTime=GETDATE() WHERE id=@Old_Id   AND OutTime IS NULL");
                    sb.AppendLine(" --调换  ");
                    sb.AppendLine(" UPDATE Basic_boar SET	dormId='"+ DormId + "' , corralId='"+ CorralId + "' WHERE id='"+ bid + "'  ");
                    sb.AppendLine(" --入舍  ");
                    sb.AppendLine(" INSERT INTO dbo.Basic_Boar_changeLog  ");
                    sb.AppendLine(" (  ");
                    sb.AppendLine("     id,  ");
                    sb.AppendLine("     BoarId,  ");
                    sb.AppendLine("     InDormId,  ");
                    sb.AppendLine("     InCorralId,  ");
                    sb.AppendLine("     InTime,   ");
                    sb.AppendLine("     accpetPerson,  ");
                    sb.AppendLine("     remarks  ");
                    sb.AppendLine(" )  ");
                    sb.AppendLine(" VALUES  ");
                    sb.AppendLine(" (   NEWID(),        -- id - varchar(50)  ");
                    sb.AppendLine("     '"+bid+"',        -- BoarId - varchar(50)  ");
                    sb.AppendLine("     '"+ DormId + "',        -- InBormId - varchar(50)  ");
                    sb.AppendLine("     '"+ CorralId + "',        -- InCorralId - varchar(50)  ");
                    sb.AppendLine("     GETDATE(), -- InTime - datetime   ");
                    sb.AppendLine("     '"+emp_name+"',        -- accpetPerson - varchar(50)  ");
                    sb.AppendLine("     '入舍'         -- remarks - varchar(50)  ");
                    sb.AppendLine("     )  ");
                    sb.AppendLine("   ");
                    sb.AppendLine("   ");
                    try
                    {
                        DBUtility.DbHelperSQL.ExecuteSql(sb.ToString());
                    }
                    catch (Exception ex) {
                      return  XhdResult.Error(ex.Message).ToString();
                    }
                }



            }
             
            return XhdResult.Success().ToString();
        }

        public string ChangeCheck(string dormId,string CorralId,string id )
        {
           string sql=(" SELECT * FROM dbo.Basic_boar WHERE dormId='" + dormId + "' AND corralId='" + CorralId + "' AND id !='"+id+"'   ");
            DataSet ds = DBUtility.DbHelperSQL.Query(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
               return XhdResult.Error("调入舍栏已被"+ds.Tables[0].Rows[0]["barcode"].ToString()+"使用!").ToString();
            }
            else return XhdResult.Success().ToString();
        }

        public string GetChangeCheckData(string bid )
        {
            string sql = (" SELECT * FROM dbo.Basic_boar WHERE id='" + bid + "'   ");
            DataSet ds = DBUtility.DbHelperSQL.Query(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataToJson.DataToJSON(ds);
            }
            else return "{}";
        }
        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " InTime";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "desc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            if (!string.IsNullOrEmpty(request["bid"]))
                serchtxt += $" and BoarId='{PageValidate.InputText(request["bid"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限
            DataSet ds = category.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);

        }

        public string tree()
        {
            DataSet ds = category.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString("root", ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string combo(string id)
        {
            DataSet ds = category.GetList($"1=1 and ProductId='" +id+"'");
            var str = new StringBuilder();
            str.Append("[");
            //str.Append("{\"id\":\"root\",\"text\":\"无\",\"d_icon\":\"\"},");
            str.Append(GetTreeString(id, ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = category.GetList($" id='{id}' ");
            return DataToJson.DataToJSON(ds);

        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return "false";
            id = PageValidate.InputText(id, 50);
          

            bool isdel = category.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误！").ToString();

            //日志
            string EventType = "产品类别删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = "";

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }


        private static string GetTreeString(string Id, DataTable table)
        {
            DataRow[] rows = table.Select($"ProductId='{Id}'");

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                str.Append("{\"id\":\"" + (string)row["id"] + "\",\"text\":\"" + (string)row["SeriesName"] + "\",\"d_icon\":\"../../" + (string)row["def1"] + "\"");

                //if (GetTreeString((string)row["id"], table).Length > 0)
                //{
                //    str.Append(",\"children\":[");
                //    str.Append(GetTreeString((string)row["id"], table));
                //    str.Append("]},");
                //}
                //else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }
    }
}
